<?php

namespace App\Models;

use App\User;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Silber\Bouncer\Database\Ability;
use Silber\Bouncer\Database\HasRolesAndAbilities;

class Hospital extends Model implements AuthenticatableContract
{
    use Authorizable, HasRolesAndAbilities, Authenticatable, SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $table = 'tn_scene';

    /**
     * 医院下的病历
     */
    public function medicalRecords()
    {
        $this->hasMany(MedicalRecord::class);
    }

    /**
     * 医院下的医生
     * @param array $columns
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function doctors(array $columns = ['*'])
    {
        return $this->user()->withoutGlobalScope('role')
                    ->whereIn('type', [0, 2, 3, 4])->select($columns);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function user()
    {
        return $this->hasMany(User::class);
    }

    /**
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function scopeHasDoctors(Builder $builder)
    {
        return $builder->whereHas('user', function (Builder $builder) {
                $builder->onlyDoctors();
            }, '>', 0
        );
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function patients()
    {
        return $this->hasMany(Patient::class);
    }

    /**
     * @param $ability
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function whoHasAbility($ability)
    {
        $model = (new Ability())->where(['name' => $ability])->first();

        return $model->morphedByMany(Hospital::class, 'entity', 'permissions');
    }

    public function isCn()
    {
        return $this->type == 2;
    }
    public function isWestern()
    {
        return $this->type == 1;
    }

    public function isWesternAndCn()
    {
        return $this->type == 3;
    }
    /* tds create */
    /*
     * param hospitalId int
     * return type int
     * */
    public function getTypeByHospitalId($hospitalId)
    {
        $hospitalInfo = $this->select('type')
            ->where('id', $hospitalId)->first()->toArray();

        if (!empty($hospitalInfo)) {
            return $hospitalInfo['type'];
        }

        return -1;
    }
}
